" if no python suppurt, finish
if has('python3')
	  set pyx=3
elseif has('python2')
  set pyx=2
 else
 echoerr "no python"
 finish
endif

" init python file
" let g:py_file = globpath(&rtp, 'script/vtp.py')
" exec 'pyxfile' .  fnameescape(g:py_file)
" let s:py_file = '../script/vtp.py'
" let s:script_path = globpath(&rtp, 'script')
" pyx import sys,vim
" pyx sys.path.append(vim.eval('s:script_path'))
"  直接导入python 太慢
if exists('g:vtp#loaded')
  finish
else
  let g:vtp#loaded = 1
endif


let s:script_path = globpath(&rtp, 'autoload/vtp')
pyx import vim
pyx import re
pyx sys.path.insert(0, vim.eval('s:script_path'))
pyx from vtp_vim import vtpManage

function! vtp#changeTargetLang(lang) abort
		let lang=a:lang
		let langList = ['zh-Hans',  'zh-Hant', 'en']
		if index(langList, lang) > -1
			let g:vtp_target_lang = lang
		else
			echoerr('不支持该语言' . lang)
		endif
endfunction

function! s:handleError(error) abort
	echo a:error
endfunction

function! vtp#translateCursorHover() abort
  pyx vtpManage.translateCursorHover()
endfunction

function! vtp#translateCursorReplace() abort
  pyx vtpManage.translateCursorReplace()
endfunction

function! vtp#regexpReplace() abort
pythonx << EOF
reg=vim.eval('g:vtp_regexp')
def vtp_replace(line):
  m=re.search(reg, line)
  if m:
    res = vtpManage.translate(m.group())
    if res is not None:
	    return line.replace(m.group(), res['translate_reault'])
    else:
	    return line
EOF
'<,'>pyxdo return vtp_replace(line)
endfunction

function! vtp#handleTranslateResult(msg)
  if exists('a:msg')
    let msg = eval(a:msg)
    if has('popupwin')
      call s:showPopup({
            \ 'title': g:vtp_engine,
            \ 'body': msg['translate_reault'],
            \ })
    else
      echo msg['translate_reault']
    endif
  endif
endfunction


function! s:showPopup(msg) abort
  let msg = a:msg
  let config = {
        \ "pos"     : 'botleft',
        \ "line"    : 'cursor-1',
        \ "col"     : 'cursor',
        \ "moved"   : 'WORD',
        \ "padding" : [0,1,0,1],
        \ "border"  : [],
        \ "borderchars": ['-', '|', '-', '|', '┌', '┐', '┘', '└'],
        \}
  let title = printf('【%s】', msg['title'])
  let body = printf('[%s]:%s',g:vtp_target_lang,msg['body'])
  let winid = popup_create(title, config)
  let bufnr = winbufnr(winid)
  call setbufline(bufnr, 2, body)
  call setbufvar(bufnr, '&filetype', 'vtp')
endfunction
